﻿using System.Configuration;
using System.Data.SqlClient;
using System.Reflection;
using System.Web.Configuration;
using CodingBlog.UI.Models.Install;

namespace CodingBlog.UI.Helpers
{
    public class InstallHelper
    {
        public void UpdateConnectionStringInWebConfig(InstallModel model)
        {
            typeof(ConfigurationElementCollection).GetField("bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic).
                SetValue(ConfigurationManager.ConnectionStrings, false);

            var builder = new SqlConnectionStringBuilder
            {
                DataSource = model.DatabaseDataSource,
                InitialCatalog = model.DatabaseName,
                UserID = model.DatabaseLogin,
                Password = model.DatabasePassword
            };

            var config = WebConfigurationManager.OpenWebConfiguration("~");

            var section = config.GetSection("connectionStrings") as ConnectionStringsSection;

            var connectionStringName = "CodingBlogContext";
            var connecionProvider = "System.Data.SqlClient";

            if (section.ConnectionStrings[connectionStringName] != null)
            {
                section.ConnectionStrings[connectionStringName].ConnectionString = builder.ConnectionString;
                section.ConnectionStrings[connectionStringName].ProviderName = connecionProvider;
            }
            else
            {
                section.ConnectionStrings.Add(new ConnectionStringSettings(connectionStringName, builder.ConnectionString,
                                                                           connecionProvider));
            }

            config.Save();
        } 
    }
}